<?php
/**
 * @version 	1.0 build 1
 * @package 	kareebu Secure
 * @copyright 	(c) 2010 www.kareebu.com
 * @license		GNU/GPL, http://www.gnu.org/licenses/gpl-3.0.html
 */
defined('_JEXEC') or die('Restricted access');

jimport('joomla.plugin.plugin');

class plgSystemkSecure extends JPlugin
{
	var $params;
	/**
	 * Constructor
	 *
	 * For php4 compatability we must not use the __constructor as a constructor for plugins
	 * because func_get_args ( void ) returns a copy of all passed arguments NOT references.
	 * This causes problems with cross-referencing necessary for the observer design pattern.
	 *
	 * @param object $subject The object to observe
	 * @since 1.5
	 */
	function plgSystemkSecure(& $subject, $config)
	{
		parent::__construct($subject, $config);
		JPlugin::loadLanguage('plg_system_ksecure', JPATH_ADMINISTRATOR);
		
		$plugin =& JPluginHelper::getPlugin('system', 'ksecure');
		$this->params = new JParameter($plugin->params);
	}
	
	function onAfterDispatch()
	{
		global $mainframe;
		
		if (!$mainframe->isAdmin()) return;
		if (!$this->params->get('enabled')) return;
		if (!$this->params->get('password')) return;
		
		$session = JFactory::getSession();
		if ($session->get('ksecure')) return;
		
		// compat - 0
		// http   - 1
		
		// http
		if ($this->params->get('mode'))
		{
			$logged = @$_SERVER['PHP_AUTH_PW'] == $this->params->get('password');
			if (!$logged)
			{
				header('WWW-Authenticate: Basic realm="'.$mainframe->getCfg('sitename').'"');
				header('HTTP/1.0 401 Unauthorized');
			
				$mainframe->redirect(JURI::root());
			}
			
		}
		// compat
		else
		{
			$logged = isset($_GET[$this->params->get('password')]);
			if (!$logged)
			{
				$mainframe->redirect(JURI::root());
			}
		}
		
		if ($logged)
			$session->set('ksecure', true);
	}
}